package com.example.house.common.config.listener;

import com.example.house.common.config.redis.RedisOperation;
import com.example.house.data.entity.DictionaryItem;
import com.example.house.data.entity.DictionaryType;
import com.example.house.data.service.DictionaryItemService;
import com.example.house.data.service.DictionaryTypeService;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;

import java.util.List;

public class ApplicationStartup implements ApplicationListener<ContextRefreshedEvent> {
    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
        //注入redis操作类
        RedisOperation redisOperation = contextRefreshedEvent.getApplicationContext().getBean(RedisOperation.class);
        //字典实现类
        DictionaryTypeService dictionaryTypeService = contextRefreshedEvent.getApplicationContext().getBean(DictionaryTypeService.class);
        DictionaryItemService dictionaryItemService = contextRefreshedEvent.getApplicationContext().getBean(DictionaryItemService.class);

        /**
         * 1.先从数据库查询出字典数据
         * 2.将字典数据保存redis
         */
        List<DictionaryType> dictionaryTypeAll = dictionaryTypeService.findAll();
        for (DictionaryType dictionaryType:dictionaryTypeAll) {
            List<DictionaryItem> dictionaryItems = dictionaryType.getDictionaryItems();
            if (dictionaryItems.size()==1){
                redisOperation.set(dictionaryType.getCode(),dictionaryItems.get(0));
            }else{
                redisOperation.set(dictionaryType.getCode(),dictionaryItems);
            }
        }
    }
}
